<template>
  <div id="cart">
    <van-nav-bar title="购物车" :right-text="'已选中(' + checkedNum + ')件'" />
    <ul>
      <li v-for="(item, index) in goodsListArr" :key="index">
        <van-checkbox-group
          v-model="result"
          class="che-box"
          ref="checkboxGroup"
        >
          <van-checkbox class="che-box-item" :name="item.id"></van-checkbox>
        </van-checkbox-group>
        <van-card
          class="card"
          :num="item.number"
          :price="item.price * item.number + '.00'"
          :title="item.goodsName"
          :thumb="item.picUrl"
          @click="openitem(item)"
        >
          <template #desc>
            <div
              @click.stop="changeConfig(item, index)"
              :style="{ marginTop: '10px' }"
            >
              选择规格
            </div>
          </template>
          <template #footer>
            <span
              @click.stop="delCart(item, index)"
              :style="{ paddingTop: '5px' }"
              >删除</span
            >
          </template>
        </van-card>
      </li>
    </ul>

    <van-submit-bar
      class="submit-box"
      :price="finalPrice * 100"
      button-text="去结算"
      @submit="onSubmit"
    >
      <van-checkbox v-model="isAllChecked">全选</van-checkbox>
    </van-submit-bar>

    <van-sku v-model="show" reset-stepper-on-hide :sku="sku" :goods="goods">
      <template #sku-stepper>
        <van-cell title="我要买">
          <template v-slot:default>
            <van-stepper v-model="proNum" />
          </template>
        </van-cell>
      </template>
      <!-- 自定义 sku actions -->
      <template #sku-actions="">
        <div class="van-sku-actions">
          <van-button
            square
            size="large"
            type="warning"
            @click="onPointClicked"
          >
            确认
          </van-button>
        </div>
      </template>
    </van-sku>
  </div>
</template>

<script>
import {
  NavBar,
  SubmitBar,
  Checkbox,
  Card,
  Stepper,
  CheckboxGroup,
  sku,
  Button,
  Cell,
  Toast,
} from "vant";
import {
  getShoppingCart,
  delShoppingCart,
  toggleChooseGoods,
  updateShoppingCart,
} from "@/network/index.js";
export default {
  name: "ShoppingCart",
  data() {
    return {
      result: [],
      checked: false, //全选按钮状态
      show: false, //sku展示状态
      goodsListArr: [], //商品信息
      goodId: 0, //商品id
      proIndex: 0, //当前选中规格商品的索引
      sku: {
        // 数据结构见下方文档
        tree: [
          {
            k: "规格",
            k_s: "s1",
            v: [
              {
                id: "1",
                name: "标准",
              },
            ],
          },
        ],
        // 所有 sku 的组合列表
        list: [
          {
            id: 0,
            s1: "1",
            price: 0,
            stock_num: 1100000, // 当前 sku 组合对应的库存
          },
        ],
        price: "100.00", // 默认价格（单位元）
        stock_num: 2270000,
      },
      goods: {
        // 数据结构见下方文档
        picture: "",
      },
      proNum: 0, //当前商品数量
    };
  },
  watch: {
    goodsListArr: {
      handler(newVal, oldVal) {
        let total = 0;
        for (let i of this.goodsListArr) {
          if (i.checked) {
            total += 1;
          }
        }
        if (total === this.goodsListArr.length) {
          this.checked = true;
        } else {
          this.checked = false;
        }
      },
      deep: true, //深度监听
    },
    result: {
      handler(val) {
        //循环查出有的元素然后发送请求
        for (let i of this.goodsListArr) {
          //查询购物车列表
          if (!val.includes(i.id)) {
            //如果当前result数组不包含的id说明是被取消选中的
            const info = {
              //
              productIds: [i.productId],
              isChecked: false,
            };
            toggleChooseGoods(info);
          } else {
            const info = {
              //
              productIds: [i.productId],
              isChecked: true,
            };
            toggleChooseGoods(info);
          }
        }
      },
    },
  },
  computed: {
    checkedNum() {
      //已经选中多少件商品
      return this.result.length; //返回result的长度即为选中的商品
    },
    finalPrice() {
      let totalPrice = 0;
      //遍历result 查询每个元素在 商品购物车数组里面是否存在 如果存在就返回当前项的价格
      for (let i of this.result) {
        for (let j of this.goodsListArr) {
          if (i === j.id) {
            totalPrice += j.number * j.price;
          }
        }
      }

      return totalPrice;
    },
    isAllChecked: {
      //是否全选
      get() {
        if (this.goodsListArr.length !== 0) {
          //如果当前购物车不为空
          //如果result的长度(即选中的商品数组)和购物车商品数组长度一样说明已经全部选中
          return this.result.length === this.goodsListArr.length ? true : false;
        } else {
          return false; //当前购物车如果为空直接返回false取消全选按钮选中
        }
      },
      set(newVal) {
        // console.log(newVal);
        if (newVal) {
          this.result = [];
          for (let i of this.goodsListArr) {
            //根据全选把购物车id放进result数组方便后续操作
            console.log(i);
            this.result.push(i.id);
          }
        } else {
          //如果是取消全选则把result清空
          this.result = [];
        }
      },
    },
  },
  components: {
    [NavBar.name]: NavBar,
    [SubmitBar.name]: SubmitBar,
    [Checkbox.name]: Checkbox,
    [Card.name]: Card,
    [CheckboxGroup.name]: CheckboxGroup,
    [sku.name]: sku,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [Stepper.name]: Stepper,
    [Toast.name]: Toast,
  },
  methods: {
    async onPointClicked() {
      //sku点击确认时
      const goods = this.goodsListArr[this.proIndex]; 
      const info = {
        productId: goods.productId,
        goodsId: goods.goodsId,
        number: this.proNum,
        id: goods.id,
      };
      const { data } = await updateShoppingCart(info); //更新购物车
      if (data.errno === 0) {
        this.show = false; //关闭sku
      }
      this.getCart()
    },
    //点击下订单
    onSubmit() {
      this.$router.push({ name: "OrderCreate" });
    },
    //选择规格
    changeConfig(item, index) {
      this.proIndex = index; //更改索引
      this.proNum = item.number; //更改数量
      this.goods.picture = item.picUrl; //把item里的图片放进sku
      this.sku.list[0].price = (item.price * 100).toFixed(2); //价格也放进sku
      this.show = true; //开启sku
    },
    //获取购物车商品
    async getCart() {
      const {
        data: { data },
      } = await getShoppingCart();
      
      if (data) {
       this.result = []
        for(let i of data.cartList) {
          if(i.checked) {
            this.result.push(i.id)
          }
        }
        this.goodsListArr = data.cartList; //保存进data
      }
    },
    //删除购物车商品
    async delCart(item, index) {
      console.log(item);
      const { data } = await delShoppingCart({ productIds: [item.productId] });
      if (data.errno === 0) {
        this.goodsListArr.splice(index, 1);
        if(item.checked) { //如果是已经选中的删除
          const idx = this.result.indexOf(item.id)//查询所对应result里面的子项索引
          this.result.splice(idx,1)//进行删除

        }
        setTimeout(() => {
          Toast.success("删除成功");
        }, 200);
      }
    },
    //打开商品详情
    openitem(item) {
      this.$router.push({
        //重载页面且重新传参
        name: "GoodsDetail",
        query: {
          id: item.goodsId,
        },
      });
    },
  },
  created() {
    //组件创建时调用接口获取购物车数据
    this.getCart();
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
#cart {
  background: rgb(242, 242, 242);
  height: 92.5vh;
}
.van-submit-bar {
  bottom: 50px;
}
.pro-box {
  display: flex;
  align-items: center;
}
.van-card__title {
  margin: 5px auto;
  font-size: 16px;
}
ul {
  li {
    border-radius: 15px;
    background: #fff;
    overflow: hidden;
    display: flex;
    justify-content: center;
    margin: 10px 20px;
    .che-box {
      width: 6%;
      // background: #fafafa;
      display: flex;
    }
    .card {
      flex: 0.9;
      background: #fff;
      //  box-sizing: border-box;
    }
  }
}
.delete-button {
  height: 100%;
}
</style>

